import { Notification } from 'element-ui'
import store from '~/store'

var clientId = 0;

const Screening = {
    socket:null,
    initialize: function() {
        let webSocketUrl = config.websocket_url
        Screening.connect(webSocketUrl);
    },
    connect:function(host){    
        if ('WebSocket' in window) {
            Screening.socket = new WebSocket(host);
        } else if ('MozWebSocket' in window) {
            Screening.socket = new MozWebSocket(host);
        } else {
            console.log('错误，这个浏览器不支持websocket');
            return;
        }
        Screening.socket.onopen = function(msg) {
            console.log('websocket 连接被打开');
        };
        Screening.socket.onclose = function() {
            console.log('WebSocket 关闭');
            //setTimeout("location.reload()",3000);
        };
        Screening.socket.onerror = function(event) {
            //onerror(event);
            console.log(event);
        };
        //seat.type 类型：【1：选中、2：取消、3：已购买（已订票，撤销）、4：清空、5解锁（特殊处理）8：取票】
        Screening.socket.onmessage = function(message) {
            try{
                console.log(message.data);
			    let msg =  JSON.parse(message.data);
                if(msg.type === 'duplicate'){
                    Notification.error({
                        title: '重票提醒',
                        message: msg.data,
                        duration:0
                    })    
                }else if(["addCart","lockSeat","unLockSeat","reduceCart","removeCart","clearCart","submitOrder","orderPaid","closeOrder","refundTicket","LongBird"].includes(msg.type)){
                    store.dispatch("board/fetchCurrentArrange");
                }
            }catch(err){
                console.log('数据解析失败，请检查数据结构');
            }
        }
    },
    sendMessage:function(msg){
        try{
            console.log(msg)
            this.socket.send(JSON.stringify(msg));
        }catch(err){
            console.log('websocket推送失败',err);
        }
    }
};
export default Screening;